package cn.cvs.servlet;

import cn.cvs.dao.MovieMapper;
import cn.cvs.pojo.Movie;
import cn.cvs.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet (urlPatterns = "/MovieLimitServlet")
public class MovieListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        SqlSession sqlSession = MyBatisUtil.createSqlSession();
        MovieMapper movieMapper = sqlSession.getMapper(MovieMapper.class);
        int pageSize = 2;
        int pageZym = 0;
        int pageNo=1;
        String pageNo1 = req.getParameter("pageNo");
        if (req.getParameter("pageNo")!=null){
            pageNo=Integer.parseInt(req.getParameter("pageNo"));
        }
        try {
            int count = movieMapper.Count();
            pageZym=(count%pageSize==0)?count/pageSize:count/pageSize+1;

            req.getSession().setAttribute("pageNo",pageNo);
            req.getSession().setAttribute("count",count);
            req.getSession().setAttribute("pageZym",pageZym);
            List<Movie> movies = movieMapper.limit(pageNo,pageSize);
            req.getSession().setAttribute("list",movies);
            req.getRequestDispatcher("movieList.jsp").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
